﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AIS.SDK.Api.ApiResponses;
using AIS.SDK.Common;
using AIS.SDK.Handler;
using AISservice.Common;
using Common;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;

namespace AISservice.Controllers
{
    [Route("api/v1/[controller]/[action]")]
    [ApiController]
    public class OAuthController : ControllerBase
    {

        [HttpPost]
        public ActionResult<MQResponse> GetToken(dynamic objpram)
        {
             
            Log4Net.Debug(objpram);
            string username = objpram["username"].ToString();
            string password = objpram["password"].ToString();
            Console.WriteLine($"请求Token:{username}");

            MQResponse execresult = new MQResponse() { ResponseCode = "200" };
            AccessTokenResponse response = new AccessTokenResponse();
            try
            {
                if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password))
                {
                    throw new MQException("401","请求的用户名或密码为空！");
                }
                response.JsonString = (string)CacheUtil.Get(username);
                if (string.IsNullOrWhiteSpace(response.JsonString))
                {
                    Console.WriteLine($"请求Token:{username}");
                    response = AISClientHandler.Instance.Tokenrequest(username, password, "AISClient", "*ALL", GlobalVariables.GetAISenvironment());
                    CacheUtil.Set(username, response.JsonString,900);

                }
                execresult.Message = response.JsonString;
                Console.WriteLine($"{DateTime.Now.ToString()} username:{username}  Token:{SomeHandler.GetToken(username)}");
            }
            catch (MQException x)
            {
                Log4Net.Error($"请求异常:{x.Message}");
                Console.WriteLine($"请求异常:{x.Message}");
                execresult.ResponseCode = CommonHandler.GetException(x.Message, "CODE", x.ExceptionCode).ToString();
                execresult.Result = CommonHandler.GetException(x.Message, "DESC", x.Message).ToString();
            }
            return execresult;
        }

        [HttpPost]
        public ActionResult<MQResponse> ValidateToken(dynamic objpram)
        {
            Log4Net.Debug(objpram);
            string token = objpram["token"].ToString();
            MQResponse execresult = new MQResponse() { ResponseCode = "200" };
            bool response = AISClientHandler.Instance.ValidateToken(token);
            if (!response)
            {
                execresult.ResponseCode = "403";
            }
            execresult.Result = response.ToString();
            return execresult;
        }


        
    }
}